package cn.sptpc.service.impl;

import cn.sptpc.dao.DepartmentDao;
import cn.sptpc.dao.GroupDao;
import cn.sptpc.dao.impl.DepartmentDaoI;
import cn.sptpc.dao.impl.GroupDaoI;
import cn.sptpc.entity.java.Department;
import cn.sptpc.entity.java.Group;
import cn.sptpc.entity.java.User;
import cn.sptpc.entity.web.JConsoleEntity;
import cn.sptpc.entity.web.JDepartmentAllEntity;
import cn.sptpc.entity.web.JMsgEntity;
import cn.sptpc.service.DepartmentService;
import com.google.gson.Gson;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class DepartmentServiceI implements DepartmentService {
    private DepartmentDao dao = new DepartmentDaoI();
    private GroupDao groupDao=new GroupDaoI();
    @Override
    public String queryCount() {
       return null;
    }

    @Override
    public String getAllDepartment(HttpServletRequest request) {
        List<Department> allDepartment = new ArrayList<>();
        User user = (User) request.getSession().getAttribute("user");
        if (user.getPermissions() == 0){
            allDepartment = dao.getAllDepartment();
        }else {
            Department department = new Department();
            department.setDepartmentName(user.getDepartment());
            department.setId(user.getDepartmentId());
            allDepartment.add(department);
        }

        JDepartmentAllEntity entity = new JDepartmentAllEntity();
        entity.setData(allDepartment);
        Gson gson = new Gson();
        return gson.toJson(entity);
    }

    public String getAllDepartment(){
            List<Department> allDepartment = dao.getAllDepartment();
        JDepartmentAllEntity entity = new JDepartmentAllEntity();
        entity.setData(allDepartment);
        Gson gson = new Gson();
        return gson.toJson(entity);
    }

    @Override
    public String insertDepartment(HttpServletRequest request) {
        String name = request.getParameter("name");
        String introduction = request.getParameter("introduction");
        String[] groups = request.getParameter("group").split(",");
        Department department = new Department();
        department.setDepartmentName(name);
        department.setDepartmentIntroduction(introduction);
        Integer i = dao.insertDepartment(department);
        if (i!=null){
            department.setId(dao.queryDepartment(name).getId());
            for (String group : groups){
                Group groupe = new Group();
                groupe.setDepartmentId(department.getId());
                groupe.setGroup(group);
                groupDao.insertGroup(groupe);
            }
            JMsgEntity entity= new JMsgEntity();
            entity.setCode(0);
            entity.setMsg("添加成功");
            return new Gson().toJson(entity);
        }
        return null;
    }
}
